import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable, throwError, of, zip } from 'rxjs'
import { catchError, map, mergeMap, concatMap } from 'rxjs/operators'

import { GroupService } from './group.service'
import { IGroupQueryParams, IGroupPagination, AgentFull, Agent } from '@shared/interfaces/group'
import { SERVER_URL, COMB_URL } from 'app/utils/contraints'
import { preProcessParams, encodeParams } from '@shared/decorators'
import { IResponse } from '@shared/interfaces/response'
import { DataService } from '@shared/services/data.service'
import { generateOptions } from 'app/utils/helpers'

@Injectable()
export class GroupAlinterService implements GroupService {
  constructor(
    public dataService: DataService,
    private http: HttpClient,
  ) {}

  @preProcessParams()
  @encodeParams()
  public getList(params: IGroupQueryParams, str?: string): Observable<IGroupPagination> {
    const url = `${COMB_URL}/camel/agents?${str}`
    return this.http.get<IGroupPagination>(url).pipe(catchError(err => throwError(err)))
  }

  getOne(agentCode: string): Observable<Agent> {
    // const url = `${SERVER_URL}/agent/find?page=1&size=1&agentCode=${code}`
    const url = `${COMB_URL}/camel/agent/${agentCode}`
    return this.http
      .get<Agent>(url, {
        withCredentials: true,
      })
      .pipe(
        catchError(err => throwError(err)),
      )
  }

  create(agentFull: AgentFull): Observable<IResponse> {
    // const url = `${SERVER_URL}/agent/save`
    const url = `${COMB_URL}/camel/agent`

    return this.http.post<IResponse>(url, agentFull).pipe(
      catchError(err => throwError(err))
    )
  }

  update(agent: Agent, agentCode: string): Observable<Agent> {
    // const url = `${SERVER_URL}/agent/update`
    const url = `${COMB_URL}/camel/agent/${agentCode}`

    return this.http
      .put<Agent>(url, agent, { withCredentials: true })
      .pipe(
        catchError(err => throwError(err)),
      )
  }

  delete(agentCode: string): Observable<boolean> {
    // const url = `${SERVER_URL}/agent/delete?agentCode=${code}`
    const url = `${COMB_URL}/camel/agent${agentCode}`
    return this.http
      .post<IResponse>(url, {
        withCredentials: true,
      })
      .pipe(
        map(res => {
          if (res.status !== 0) {
            throw new Error(res.message)
          }

          return true
        }),
        catchError(err => {
          return of(false)
        }),
      )
  }

  /** 冻结 */
  freeze(agentCode: string): Observable<boolean> {
    const url = `${COMB_URL}/camel/agent/${agentCode}/freeze`
    return this.http.put<boolean>(url, {})
  }

  /** 解冻 */
  unfreeze(agentCode: string): Observable<boolean> {
    const url = `${COMB_URL}/camel/agent/${agentCode}/unfreeze`
    return this.http.put<boolean>(url, {})
  }
}
